
package cn.mrcode.wxsdk.core.dialogue.common.util;

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 
 * @ClassName: HttpKit 
 * @Description: https 请求 微信为https的请求 
 * @author zq 
 *
 * @version V0.1   
 * @date 2014年12月4日 上午9:40:23
 */
public class HttpKit {
	private static final String DEFAULT_CHARSET = "UTF-8";

	/**
	 * @return 返回类型:
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 * @description 功能描述: get 请求
	 */
	public static String get(AsyncHttpClient http ,String url, Map<String, String> params, Map<String, String> headers) throws IOException,
			ExecutionException, InterruptedException {
		AsyncHttpClient.BoundRequestBuilder builder = http.prepareGet(url);
		builder.setBodyEncoding(DEFAULT_CHARSET);
		if (params != null && !params.isEmpty()) {
			for (Map.Entry<String,String> ent :params.entrySet() ){
				builder.addParameter(ent.getKey(), ent.getValue());
			}
		}
		
		if (headers != null && !headers.isEmpty()) {
			Set<String> keys = headers.keySet();
			for (String key : keys) {
				builder.addHeader(key, params.get(key));
			}
		}
		Future<Response> f = builder.execute();
		String body = f.get().getResponseBody(DEFAULT_CHARSET);
		return body;
	}
	

	/**
	 * @return 返回类型:
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 * @description 功能描述: get 请求
	 */
	public static String get(AsyncHttpClient http ,String url) throws KeyManagementException, NoSuchAlgorithmException,
			NoSuchProviderException, UnsupportedEncodingException, IOException, ExecutionException,
			InterruptedException {
		return get(http ,url, null);
	}
	

	/**
	 * @return 返回类型:
	 * @throws IOException
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 * @throws UnsupportedEncodingException
	 * @description 功能描述: get 请求
	 */
	public static String get(AsyncHttpClient http ,String url, Map<String, String> params) throws KeyManagementException,
			NoSuchAlgorithmException, NoSuchProviderException, UnsupportedEncodingException, IOException,
			ExecutionException, InterruptedException {
		return get(http,url, params, null);
	}
	

	/**
	 * @return 返回类型:
	 * @throws IOException
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 * @description 功能描述: POST 请求
	 */
	public static String post(AsyncHttpClient http,String url, Map<String, String> params) throws IOException, ExecutionException,
			InterruptedException {
		AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
		builder.setBodyEncoding(DEFAULT_CHARSET);
		if (params != null && !params.isEmpty()) {
			for (Map.Entry<String,String> ent :params.entrySet() ){
				builder.addParameter(ent.getKey(), ent.getValue());
			}
		}
		Future<Response> f = builder.execute();
		String body = f.get().getResponseBody(DEFAULT_CHARSET);
		return body;
	}

	/**
	 * 
	 * @Title: postXml 
	 * @Description: 发送xml参数 
	 * @param http
	 * @param url
	 * @param xml
	 * @throws Exception
	 * @return String
	 * @version V0.1  
	 * @createDate 2015年2月6日 上午9:48:14 
	 * @updateDate 2015年2月6日 上午9:48:14
	 */
	public static String postXml(AsyncHttpClient http, String url, String xml) throws Exception {
		AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
		builder.setHeader("Content-Type", "text/xml;charset=UTF-8");
		builder.setBodyEncoding("UTF-8");
		builder.setBody(xml);
		Future<Response> f = builder.execute();
		String body = f.get().getResponseBody("UTF-8");
		return body;
	}
	 
	/**
	 * 上传媒体文件
	 * 
	 * @param url
	 * @param file
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 * @throws KeyManagementException
	 */
	/*
	 * public static String upload(String url, File file) throws IOException,
	 * NoSuchAlgorithmException, NoSuchProviderException,
	 * KeyManagementException, ExecutionException, InterruptedException {
	 * AsyncHttpClient http = new AsyncHttpClient();
	 * AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
	 * builder.setBodyEncoding(DEFAULT_CHARSET); String BOUNDARY =
	 * "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // 定义数据分隔线
	 * builder.setHeader("connection", "Keep-Alive");
	 * builder.setHeader("user-agent",
	 * "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"
	 * ); builder.setHeader("Charsert", "UTF-8");
	 * builder.setHeader("Content-Type", "multipart/form-data; boundary=" +
	 * BOUNDARY); byte[] end_data = ("\r\n--" + BOUNDARY +
	 * "--\r\n").getBytes();// 定义最后数据分隔线 builder.setBody(new
	 * UploadEntityWriter(end_data, file));
	 * 
	 * Future<Response> f = builder.execute(); String body =
	 * f.get().getResponseBody(DEFAULT_CHARSET); http.close(); return body; }
	 */

//	/**
//	 * 下载资源
//	 *
//	 * @param url
//	 * @return
//	 * @throws java.io.IOException
//	 */
//	public static Attachment download(String url) throws ExecutionException, InterruptedException, IOException {
//		Attachment att = new Attachment();
//		AsyncHttpClient http = new AsyncHttpClient();
//		AsyncHttpClient.BoundRequestBuilder builder = http.prepareGet(url);
//		builder.setBodyEncoding(DEFAULT_CHARSET);
//		Future<Response> f = builder.execute();
//		if (f.get().getContentType().equalsIgnoreCase("text/plain")) {
//			att.setError(f.get().getResponseBody(DEFAULT_CHARSET));
//		} else {
//			BufferedInputStream bis = new BufferedInputStream(f.get().getResponseBodyAsStream());
//			String ds = f.get().getHeader("Content-disposition");
//			String fullName = ds.substring(ds.indexOf("filename=\"") + 10, ds.length() - 1);
//			String relName = fullName.substring(0, fullName.lastIndexOf("."));
//			String suffix = fullName.substring(relName.length() + 1);
//
//			att.setFullName(fullName);
//			att.setFileName(relName);
//			att.setSuffix(suffix);
//			att.setContentLength(f.get().getHeader("Content-Length"));
//			att.setContentType(f.get().getContentType());
//			att.setFileStream(bis);
//		}
//		http.close();
//		return att;
//	}

	public static String post(AsyncHttpClient http,String url, String s) throws IOException, ExecutionException, InterruptedException {
		AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
		builder.setBodyEncoding(DEFAULT_CHARSET);
		builder.setBody(s);
		Future<Response> f = builder.execute();
		String body = f.get().getResponseBody(DEFAULT_CHARSET);
		return body;
	}
	/**
	 * 
	 * @Title: get_InputStream 
	 * @Description:  get方式请求一个连接，返回一个输入流，一般用于下载图片文件等 
	 * @param url 地址
	 * @throws IOException
	 * @throws InterruptedException
	 * @throws ExecutionException
	 * @return InputStream 返回输入流
	 *
	 * @version V0.1  
	 * @date 2014年12月4日 上午9:39:12
	 */
	public static InputStream get_InputStream(AsyncHttpClient http,String url) throws IOException, InterruptedException, ExecutionException {
		AsyncHttpClient.BoundRequestBuilder builder = http.prepareGet(url);
		builder.setBodyEncoding("UTF-8");
		Future<Response> f = builder.execute();
		Response response = f.get();
		InputStream responseBodyAsStream = response.getResponseBodyAsStream();
		return responseBodyAsStream;
	}
}